<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
                v-model="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <van-cell-group inset>
            <van-field
                v-model="rpassword"
                name="密码"
                label="重复密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <div style="margin: 16px">
            <van-button
                :disabled="btnFlag"
                round
                block
                type="primary"
                native-type="submit"
            >
                注册
            </van-button>
        </div>
    </van-form>
</template>

<!--
    1. 密码和重复输入密码为空的时候 不能点击注册
    2. 密码和重复输入密码不一致的时候 不能点击注册

    3. 注册按钮点击完毕后, 将数据发送给后端
        * 失败: 提醒用户失败原因
        * 成功: 跳转到登录页
-->

<script setup lang="ts">
import { ref, computed } from "vue";
import type { Ref } from "vue";
import { dofinishregister } from "@/api/register";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router'

// 创建一个 选项式 API 中的 this.$router
const router = useRouter()

const password: Ref<string> = ref("");
const rpassword: Ref<string> = ref("");

// 点击注册按钮
async function onSubmit() {
    const { data } = await dofinishregister({
        tel: window.localStorage.getItem("phoneNum") + "",
        password: password.value,
    });

    if (data.code !== "200") {
        // 提示注册失败
        return showFailToast(data.message);
    }

    // 提醒用户 注册 通过
    showSuccessToast(data.message);

    // 跳转到登录页面
    router.push("/login");
}

// 根据输入框的内容, 控制按钮能否使用
const btnFlag = computed(() => {
    // if (password.value !== "" && password.value === rpassword.value) {
    //     // 满足条件, 允许使用按钮
    //     return false
    // } else {
    //     // 不满足条件, 禁用按钮
    //     return true
    // }

    return !(password.value !== "" && password.value === rpassword.value);
});
</script>
